package cn.yzgy.yzgyoa.common.controller;


import cn.yzgy.yzgyoa.common.annotation.ApiDesc;
import cn.yzgy.yzgyoa.common.crsp.Urmf;
import cn.yzgy.yzgyoa.common.dto.LogQueryDto;
import cn.yzgy.yzgyoa.common.entity.SysLog;
import cn.yzgy.yzgyoa.common.service.impl.SysLogServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 日志表 前端控制器
 * </p>
 *
 * @author Yqsen
 * @since 2019-12-13
 */
@RestController
@RequestMapping("/common/log")
public class SysLogController extends BaseController {

    private static final String USER_NAME_COL_NAME = "user_name";
    private static final String ACTION_NAME_COL_NAME = "method";
    private static final String REQUEST_TIME_COL_NAME = "request_time";
    private static final String ID_COL_NAME = "id";
    private static final String SPLIT_CHARACTER = " ";
    private static final int COMBINE_TYPE_AND = 1;

    private final SysLogServiceImpl sysLogService;

    public SysLogController(SysLogServiceImpl sysLogService) {
        this.sysLogService = sysLogService;
    }

    @GetMapping
    @ApiDesc("查询系统日志")
    @RequiresPermissions("api:common:log:get")
    public Urmf getLogs(@RequestParam Integer page, @RequestParam Integer size, LogQueryDto dto) {
        QueryWrapper<SysLog> wrapper = new QueryWrapper<SysLog>()
                .eq(dto.getUserName() != null, USER_NAME_COL_NAME, dto.getUserName())
                .between(dto.getStartTime() != null && dto.getEndTime() != null,
                        REQUEST_TIME_COL_NAME, dto.getStartTime(), dto.getEndTime())
                .orderByDesc(ID_COL_NAME);
        // 分割关键字
        if (dto.getActionKeyword() != null && dto.getKeywordCombineType() != null) {
            String[] words = dto.getActionKeyword().split(SPLIT_CHARACTER);
            int combineType = dto.getKeywordCombineType();
            if (words.length > 0) {
                wrapper.like(ACTION_NAME_COL_NAME, words[0]);
            }
            for (int i = 1; i < words.length; i++) {
                // 过滤空项目
                if ("".equals(words[i])) {
                    continue;
                }
                int pos = i;
                if (combineType != COMBINE_TYPE_AND) {
                    wrapper.or(x -> x.like(ACTION_NAME_COL_NAME, words[pos]));
                } else {
                    wrapper.and(x -> x.like(ACTION_NAME_COL_NAME, words[pos]));
                }
            }
        }

        IPage<SysLog> logs = sysLogService.page(new Page<>(page, size), wrapper);
        return Urmf.success(getCurrentMethodName(), logs);
    }
}
